package com.momoback.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.momoback.constant.ConfigConstant;
import com.momoback.entity.*;
import com.momoback.feign.OpenFeignClient;
import com.momoback.feign.OpenFeignWXClient;
import com.momoback.repos.SystemRepository;
import com.momoback.repos.UserRepository;
import com.momoback.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URI;
import java.util.*;

@Service
public class MiniProgramService {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private OpenFeignClient openFeignClient;
    @Autowired
    private OpenFeignWXClient openFeignWXClient;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private SystemRepository systemRepository;
    private RestTemplate restTemplate;

    @PostConstruct
    public void init() {
        this.restTemplate = new RestTemplate();
    }

    public String getRegisterId() {
        Object registerObj = openFeignClient.getRegisterId();
        if (registerObj != null) {
            String[] registerArr = registerObj.toString().trim().split("=");
            if (registerArr.length == 2) {
                String registerId = registerArr[1].substring(0, registerArr[1].length() - 1);
                Object status = openFeignClient.createStatus(registerId);
                if (status == null) {
                    openFeignClient.createStatus(registerId);
                }
                return registerId;
            }
            return null;
        } else {
            return null;
        }
    }


    private String getOpenId(String code) {
        LfSystementity system = systemRepository.findByConfig(ConfigConstant.MINI_APP);
        if (system == null) {
            return null;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String appId = system.getValue();
        //小程序的 app secret (在微信小程序管理后台获取)
        String secret = system.getExtend();
        //授权（必填）
        String grant_type = "authorization_code";
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        Object res = openFeignWXClient.getOpenId(appId, secret, code, grant_type);
        if (res == null) {
            return "";
        }
        Map<String, String> resultMap = JSON.parseObject(res.toString(), Map.class);
        return resultMap.get("openid");
    }

    public Map<String, String> handleFile(String filePath, String name, String chatId) {
        JSONObject preSignJson = new JSONObject();
        preSignJson.put("action", "file");
        preSignJson.put("name", name);
        Map<String, String> preSignUrlMap = openFeignClient.preSignUrlFile(preSignJson);
        String uploadUrl = preSignUrlMap.get("url");
        String objectName = preSignUrlMap.get("object_name");
//        FileUploader.uploadFilePut(uploadUrl, filePath);

        JSONObject fileParamsJson = new JSONObject();
        fileParamsJson.put("chat_id", chatId);
        fileParamsJson.put("name", name);
        fileParamsJson.put("object_name", objectName);
        fileParamsJson.put("type", "file");
        Map<String, String> submitfiled = openFeignClient.submitfile(fileParamsJson);
//
//        String presignedUrl = submitfiled.get("presigned_url");
//
//        FileUploader.uploadFileGET(presignedUrl,filePath);

        return submitfiled;

    }

    public Object createVerifyCode(String phoneNumber) {
        JSONObject codeData = new JSONObject();
        codeData.put("action", "register");
        codeData.put("phone", phoneNumber);
        codeData.put("country_code", "+86");
        String capt = "69a2d727b69d4d5486b1a2f3df00abe0";
        String lot = "e62dc76f73e5436ebacd0e04fe9ef743";
        String pass = "1eb1f404b9b814a988164825788cbae7fc1de486b333a5c9b24f111cda3b2065";
        String captchaOutput = jwtUtil.generateToken(phoneNumber);

        codeData.put("captcha_id", capt);
        codeData.put("lot_number", lot);
        codeData.put("pass_token", pass);
        codeData.put("gen_time", String.valueOf(System.currentTimeMillis()));
        codeData.put("captcha_output", captchaOutput);
        System.out.println(codeData);
        Object res = openFeignClient.sendVerifyCode(codeData);
        if (res != null) {
            throw new RuntimeException("请稍后再试！");
        }
        return res;
    }

    public Object verifyCode(JSONObject json) {
        JSONObject res = openFeignClient.verifyPhoneCode(json);

        if (res == null) {
            throw new RuntimeException("请稍后再试！");
        }
        if (res.getString("error_type") != null) {
            throw new RuntimeException("您输入的验证码不正确");
        }
        return res;
    }

    public JSONObject verifyCodeAndLogin(WechatLoginRequest request) {
        JSONObject verifyParam = new JSONObject();
        verifyParam.put("phone", request.getPhone());
        verifyParam.put("verify_code", request.getVerifyCode());
        verifyParam.put("country_code", "+86");
        verifyParam.put("wx_user_id", null);
        //  String openId = getOpenId(request.getCode());
        JSONObject jsonObject = openFeignClient.verifyPhoneCode(verifyParam);
        if (jsonObject.get("user") != null) {
            Object userObj = jsonObject.get("user");
            System.out.println(userObj.toString());

            User user = new User();
            if (userObj instanceof JSONObject) {
                JSONObject userJson = JSONObject.parseObject(userObj.toString());

                user.setPhone(userJson.getString("phone"));
                user.setAvatarUrl(request.getAvatarUrl());
                user.setNickName(request.getNickName());
                user.setOpenid(userJson.getString("id"));
            }
            User saveUser = userRepository.findByPhone(request.getPhone());
            if (saveUser == null) {
                //新注册用户
                userRepository.save(user);
            }
            return jsonObject;
        } else {
            return null;
        }
    }

}